package com.example.mmlist2;

import static android.content.Context.MODE_PRIVATE;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.example.mmlist2.databinding.FragmentDetailBinding;
import com.example.mmlist2.storage.DatabaseHelper;
import com.example.mmlist2.storage.EncryptionUtils;
import com.example.mmlist2.storage.entity.Account;
import com.google.android.material.snackbar.Snackbar;

import java.util.Objects;


public class DetailFragment extends Fragment {

    private FragmentDetailBinding binding;
    TextView DatabaseId;
    EditText title, username, password, link, illustrate;
    String oldPassword;
    Boolean isHide;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentDetailBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        Button saveButton = view.findViewById(R.id.saveButton);
        // 获取账号信息
        title = view.findViewById(R.id.title);
        username = view.findViewById(R.id.username);
        password = view.findViewById(R.id.password);
        link = view.findViewById(R.id.link);
        illustrate = view.findViewById(R.id.illustrate);
        DatabaseId = view.findViewById(R.id.DatabaseId);

        // 获取通过Navigation传递的参数
        Bundle bundle = getArguments();
        String id = null;
        if (bundle != null) {
            id = bundle.getString("id");
        }
        if (id != null) {
            Log.d("DetailFragment", "id:" + id);
            DatabaseId.setText(id);
            try (DatabaseHelper helper = new DatabaseHelper(getContext())) {

//                    Account account = helper.getAccountById(id);
                Account account = helper.getAccountById(Integer.parseInt(id));
                oldPassword = account.getPassword();
                title.setText(account.getTitle());
                username.setText(account.getUsername());
                password.setText(account.getPassword());
                link.setText(account.getLink());
                illustrate.setText(account.getIllustrate());
            } catch (Exception e) {
                Snackbar.make(view, "获取数据异常", Snackbar.LENGTH_LONG).show();
                throw new RuntimeException(e);
            }
        }
        // 添加账号信息到数据库
        saveButton.setOnClickListener(v -> {
            //对象转字符串
            String titleStr = title.getText().toString();
            String usernameStr = username.getText().toString();
            String passwordStr = password.getText().toString();
            String linkStr = link.getText().toString();
            String illustrateStr = illustrate.getText().toString();

            // 判断输入框是否为空
            if (titleStr.isEmpty() || passwordStr.isEmpty()) {
                Toast.makeText(getContext(), "标题密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            // 添加账号信息到数据库
            Account account = new Account(usernameStr, passwordStr, titleStr, linkStr, illustrateStr);
            DatabaseHelper helper = new DatabaseHelper(getContext());
            String isAdd = DatabaseId.getText().toString();
            try {
                SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("MyPreferences", MODE_PRIVATE);
                String encodedToken = sharedPreferences.getString("pass", null);
                // 判断是添加还是修改
                if (isAdd.equals("null")) {
                    if (encodedToken != null) {
                        byte[] decodedToken = Base64.decode(encodedToken, Base64.DEFAULT);
                        helper.addAccount(account, decodedToken);
                    } else {
                        Toast.makeText(getContext(), "请先设置指纹", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    int Id = Integer.parseInt(DatabaseId.getText().toString());
                    if (passwordStr.equals(oldPassword)) {
                        // 没有修改密码，部分更新
                        helper.updateAccountById2(Id, titleStr, usernameStr, linkStr, illustrateStr);
                    } else {
                        // 修改密码，全部添加
                        if (encodedToken != null) {
                            byte[] decodedToken = Base64.decode(encodedToken, Base64.DEFAULT);
                            helper.updateAccountById1(decodedToken, Id, titleStr, usernameStr, passwordStr, linkStr, illustrateStr);
                        } else {
                            Toast.makeText(getContext(), "请先设置指纹", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                helper.close();
            } catch (Exception e) {
                Snackbar.make(v, "添加数据异常", Snackbar.LENGTH_LONG).show();
                throw new RuntimeException(e);
            }
            // 返回上一界面
            NavHostFragment.findNavController(DetailFragment.this).navigateUp();
        });

        //复制账号信息到剪切板
        ImageView copyTitle, copyUsername, copyPassword, copyLink;
        copyTitle = view.findViewById(R.id.copyTitle);
        copyUsername = view.findViewById(R.id.copyUsername);
        copyPassword = view.findViewById(R.id.copyPassword);
        copyLink = view.findViewById(R.id.copyLink);
        // 设置点击事件
        copyTitle.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) Objects.requireNonNull(getContext()).getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Label", title.getText());
            cm.setPrimaryClip(mClipData);
            Toast.makeText(getContext(), "复制标题成功", Toast.LENGTH_SHORT).show();
        });
        copyUsername.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) Objects.requireNonNull(getContext()).getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Label", username.getText());
            cm.setPrimaryClip(mClipData);
            Toast.makeText(getContext(), "复制用户名成功", Toast.LENGTH_SHORT).show();
        });
        copyPassword.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) Objects.requireNonNull(getContext()).getSystemService(Context.CLIPBOARD_SERVICE);
            String passwordStr = password.getText().toString();
            SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("MyPreferences", MODE_PRIVATE);
            String encodedToken = sharedPreferences.getString("pass", null);
            if (encodedToken != null) {
                try {
                    passwordStr = EncryptionUtils.decryptPassword(getContext(), passwordStr);
                } catch (Exception e) {
                    Toast.makeText(getContext(), "密码复制错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请先设置指纹", Toast.LENGTH_SHORT).show();
            }
            ClipData mClipData = ClipData.newPlainText("Label", passwordStr);
            cm.setPrimaryClip(mClipData);
            Toast.makeText(getContext(), "复制密码成功", Toast.LENGTH_SHORT).show();
        });
        copyLink.setOnClickListener(v -> {
            ClipboardManager cm = (ClipboardManager) Objects.requireNonNull(getContext()).getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Label", link.getText());
            cm.setPrimaryClip(mClipData);
            Toast.makeText(getContext(), "复制链接成功", Toast.LENGTH_SHORT).show();
        });

        // 显示密码
        ImageView showPassword;
        isHide = true;
        showPassword = view.findViewById(R.id.eye);
        showPassword.setOnClickListener(view1 -> {
            String isAdd = DatabaseId.getText().toString();
            // isAdd为null是添加数据状态
            if ("null".equals(isAdd)) {
                if (isHide) {
                    // 显示密码
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isHide = false;
                } else {
                    // 隐藏密码
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isHide = true;
                }
            } else {
                String passwordStr = password.getText().toString();
                // passwordStr为空时，showPassword按钮无效
                if (passwordStr.isEmpty()) {
                    return;
                }
                if (isHide) {
                    // 显示密码
                    try {
                        password.setText(EncryptionUtils.decryptPassword(requireContext(), passwordStr));
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "密码解码错误", Toast.LENGTH_SHORT).show();
                    }
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isHide = false;
                } else {
                    // 隐藏密码
                    try {
                        password.setText(EncryptionUtils.encryptPassword(requireContext(), passwordStr));
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "密码加密错误", Toast.LENGTH_SHORT).show();
                    }
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isHide = true;
                }
            }
            password.clearFocus();
        });

        // 修改密码
        password.setOnFocusChangeListener((v, hasFocus) -> {
            String isAdd = DatabaseId.getText().toString();
            if (!isAdd.equals("null")) {
                if (hasFocus) { // 获得焦点
                    if (isHide) {  //密码隐藏时
                        // 弹窗提示是否修改密码
                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                        builder.setTitle("是否需要修改密码？")
                                .setMessage("确认后，将清空密码框，请重新输入。\ntip: 在密码可见状态下，可以直接修改密码。")
                                .setPositiveButton("确定", (dialog, which) -> {
                                    Toast.makeText(getContext(), "请设置新密码", Toast.LENGTH_SHORT).show();
                                    password.setText("");
                                });

                        AlertDialog dialog = builder.create(); // 创建AlertDialog
                        dialog.setOnCancelListener(dialogInterface -> {
                            // 关闭输入法
                            Context context = getContext();
                            if (context != null && v != null) {
                                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                                if (imm != null) {
                                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                                }
                            }

                            // 使输入框失去焦点
                            password.clearFocus();
                        });
                        dialog.show(); // 显示对话框
                    }
                }
            }
        });


        //跳转链接到浏览器
        ImageView upload;
        upload = view.findViewById(R.id.upload);
        upload.setOnClickListener(v -> {
            String linkStr = link.getText().toString();
            if (linkStr.trim().isEmpty()) {
                Toast.makeText(getContext(), "请先设置链接", Toast.LENGTH_SHORT).show();
            } else if (!checkUrl(linkStr)) {
                Toast.makeText(getContext(), "检测到非链接", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(linkStr));
                startActivity(intent);
            }
        });


        return view;

    }

    //检验是否为链接
    boolean checkUrl(String str) {
        String[] protocols = {"http://", "https://"};
        for (String protocol : protocols) {
            if (str.startsWith(protocol)) {
                return true;
            }
        }

        return false;
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}